/*
 * sys.c
 *
 *  Created on: 2021年7月17日
 *      Author: dbw
 */

#include "sys.h"
#include "common.h"
#include "stm32f4xx.h"

static uint32_t tick_per_us;

void sys_init(void)
{
    tick_per_us = SystemCoreClock / 1000000L;
}

void sys_delay(uint32_t ms)
{
    uint32_t timeout = sys_get_time() + ms;
    while(sys_get_time() - timeout > UINT32_MAX / 2);
}

void sys_udelay(uint32_t us)
{
    uint32_t begin;
    uint32_t end;
    uint32_t delay;
    uint32_t reload;

    begin = SysTick->VAL;
    delay = us * tick_per_us;
    reload = SysTick->LOAD;

    if (begin >= delay)
    {
        end = begin - delay;
        while (SysTick->VAL > end && SysTick->VAL < begin);
    }
    else
    {
        end = reload + 1 - (delay - begin);
        while (SysTick->VAL < begin || SysTick->VAL > end);
    }
}

uint32_t sys_get_time(void)
{
    return HAL_GetTick();
}

